package com.wugz.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import service.IMonitorService;
import service.IStudentService;
import service.ITeacherService;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ClassController
 * @Description
 * @Author wugz
 * @Date 2020/5/9 14:40
 * @Version 1.0
 */
@RestController
public class ClassController {

    @Reference
    private IStudentService studentService;

    @Reference
    private ITeacherService teacherService;

    @Reference(timeout = 3000)
    private IMonitorService monitorService;

    @RequestMapping("/")
    public Object test(){
        System.out.println("上课了,老师说：" + teacherService.teacherSayHello()) ;
        System.out.println("学生说：" + studentService.studentSayHello()) ;
        return "success";
    }

    @RequestMapping("/monitor")
    public Object monitor(HttpServletRequest repuest) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = createThreadPoolExecutor();
        System.out.println("=========Input something on console for starting invoke");
        for (int i = 0 ;i<=2000 ;i++) {
            Thread.sleep(8);
            threadPoolExecutor.submit(() -> {
                try {
                    //调用testingOne
                    monitorService.testingOne();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threadPoolExecutor.submit(() -> {
                try {
                    monitorService.testingTwo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threadPoolExecutor.submit(() -> {
                try {
                    monitorService.testingThree();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        return "success";
    }

    public static ThreadPoolExecutor createThreadPoolExecutor() {
        int corePoolSize = 50;
        int maximumPoolSize = 50;
        long keepAliveTime = 60;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);

        return new ThreadPoolExecutor
                (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, (r, executor)
                        -> System.out.println("======Too many requests do abort"));
    }
}
